<template>
	<!-- <view class="content" :style="'background-image: url(' + $c.config.media + 'yuemini/reg_bg.png);'"> -->
	<view class="content" :style="'background-image: url(' + $c.config.media + 'yuemini/reg_bg.png);'">
		<view :style="{height:$store.state.StatusBar.statusBar + 'px'}"></view>
		<view v-if="isWXflag==true" style="height: 100rpx;"></view>
		<view class="z_index2 flex_r item" @tap="to('/pages/m-pages/m-articleList/index?type=1')">
			<view class="item-img">
				<image class="img" mode="aspectFill" style="border-radius: 50%;" :src="$c.config.imageIP + 'yuemini/ic_message_system.png'" ></image>
			</view>
			<view class="flex1 nowrap_ item-r">
				<view class="flex_r fj_b name">
					<view class="text_32">
						系统信息
					</view>
					<view class="text_22 color__">
						{{info.xitong.createtime}}
					</view>
				</view>
				<view class="text_26 color__ nowrap_ text">
					{{info.xitong.title}}
				</view>
	<!-- 			<view class="m-line">
					<m-line color="#fff" length="100%" :hairline="true"></m-line>
				</view> -->
			</view>
		</view>
		<view v-if="iswx==1" class="z_index2 flex_r item" @tap="to('/pages/m-pages/m-articleList/index?type=2')">
			<view class="item-img">
				<image class="img" mode="aspectFill" style="border-radius: 50%;"  :src="$c.config.imageIP + 'yuemini/ic_message_platform.png'"></image>
			</view>
			<view class="flex1 nowrap_ item-r">
				<view class="flex_r fj_b name">
					<view class="text_32">
						平台信息
					</view>
					<view class="text_22 color__">
						{{info.pingtai.createtime}}
					</view>
				</view>
				<view class="text_26 color__ nowrap_ text">
					{{info.pingtai.title}}
				</view>
		<!-- 		<view class="m-line">
					<m-line color="#fff" length="100%" :hairline="true"></m-line>
				</view> -->
			</view>
		</view>

		<view v-if="iswx==1" class="z_index2 flex_r item"  v-for="(item,index) in conversationList" @tap="handleRoute(item.conversationID)">
			<view class="item-img">
				<image class="img" mode="aspectFill" style="border-radius: 50%;" :src="item.setConversationAvatar"></image>
			</view>
			<view class="size_white text_20 item-UNREAD" v-if="item.unreadCount > 0">
				{{ item.unreadCount }}
			</view>
			<view class="flex1 nowrap_ item-r">
				<view class="flex_r fj_b name">
					<view class="text_32">
						{{item.conversationName}}
					</view>
					<view class="text_22 color__">
						{{item.timeago}}
					</view>
				</view>
				<view class="text_24 color__ nowrap_ text">
					{{item.lastMessage.messageForShow}}
				</view>
			<!-- 	<view class="m-line">
					<m-line color="#fff" length="100%" :hairline="true"></m-line>
				</view> -->
			</view>
		</view>


	</view>
</template>

<script>
	import {to} from '@/utils/index.js';
	export default {
	  data() {
	    return {
		 $c: this.$c,
	      show: false,
		  isWXflag:false,
		  iswx:1,
		  info:{
			xitong:{title:'',createtime:''},  
			pingtai:{title:'',createtime:''}
		  },
	      options1: [
	        {
	          text: '恢复',
	          style: {
	            backgroundColor: '#3c9cff',
	          },
	        },
	        {
	          text: '删除',
	          style: {
	            backgroundColor: '#f56c6c',
	          },
	        },
	        {
	          text: '免打扰',
	          style: {
	            backgroundColor: '#ffaa00',
	          },
	        },
	      ],
	      options4: [
	        {
	          text: '恢复',
	          style: {
	            backgroundColor: '#3c9cff',
	          },
	        },
	        {
	          text: '删除',
	          style: {
	            backgroundColor: '#f56c6c',
	          },
	        },
	        {
	          text: '提醒',
	          style: {
	            backgroundColor: '#ffaa00',
	          },
	        },
	      ],
	      options2: [
	        {
	          text: '顶置',
	          style: {
	            backgroundColor: '#3c9cff',
	          },
	        },
	        {
	          text: '删除',
	          style: {
	            backgroundColor: '#f56c6c',
	          },
	        },
	        {
	          text: '免打扰',
	          style: {
	            backgroundColor: '#ffaa00',
	          },
	        },
	      ],
	      options3: [
	        {
	          text: '顶置',
	          style: {
	            backgroundColor: '#3c9cff',
	          },
	        },
	        {
	          text: '删除',
	          style: {
	            backgroundColor: '#f56c6c',
	          },
	        },
	        {
	          text: '提醒',
	          style: {
	            backgroundColor: '#ffaa00',
	          },
	        },
	      ],
	      conversationID: '',
	      searchKey: '',
	      conversationList: [],
	      showSelectTag: false,
	    };
	  },
	  components: {
	  },
	  computed: {
	    isLogin() {
	      return this.$store.state.isLogin;
	    },
	  },
	  watch: {
	    isLogin(val) {
	      if (val) {
	        // 登入后拉去会话列表
	        this.getConversationList();
	        uni.$TUIKit.on(uni.$TUIKitEvent.CONVERSATION_LIST_UPDATED, this.onConversationListUpdated);
	      }
	    },
	  },
	  /**
	   * 生命周期函数--监听页面加载
	   */
	  onShow() {
		  // #ifdef MP-WEIXIN
		   this.isWXflag =true;
		   this.iswx= uni.getStorageSync('iswx');					   
		  // #endif
	    if (this.isLogin) {
	      // 登入后拉去会话列表
	      this.getConversationList();
	      uni.$TUIKit.on(uni.$TUIKitEvent.CONVERSATION_LIST_UPDATED, this.onConversationListUpdated);
	    }
		this.getInfo();
	  },
	  /**
	   * 生命周期函数--监听页面卸载
	   */
	  onUnload() {
	    // uni.$TUIKit.off(uni.$TUIKitEvent.SDK_READY, this.onConversationListUpdated);
	  },
	  methods: {
			to,
		async getInfo() {
			let res = await this.$c.post('/app/pingtai/getPingtaiAndXitong')
			if (res.code == 0) {
				this.info = res.data
			}
		},
		deleteConversationList: function (e, value) {
	      if (e.index == '0') {
	        const list = this.conversationList;
	        const show = list.map(item => {
	          return item.isPinned;
	        });
	        for (var item of list) {
	          if (item.conversationID == value) {
	            if (show[list.indexOf(item)] === false) {
	              // 置顶会话，v2.14.0起支持
	              uni.$TUIKit
	                .pinConversation({
	                  conversationID: value,
	                  isPinned: true,
	                })
	                .then(imResponse => {
	                  // 置顶会话成功
	                  const { conversationID } = imResponse.data; // 被置顶的会话 ID
	                  console.log(conversationID);
	                })
	                .catch(function (imError) {
	                  console.warn('pinConversation error:', imError); // 置顶会话失败的相关信息
	                });
	            }
	            if (show[list.indexOf(item)] === true) {
	              // 取消置顶会话，v2.14.0起支持
	              uni.$TUIKit
	                .pinConversation({
	                  conversationID: value,
	                  isPinned: false,
	                })
	                .then(imResponse => {
	                  // 取消置顶会话成功
	                  const { conversationID } = imResponse.data; // 被取消置顶的会话 ID
	                })
	                .catch(function (imError) {
	                  console.warn('pinConversation error:', imError); // 取消置顶会话失败的相关信息
	                });
	            }
	          }
	        }
	      }
	      if (e.index == '1') {
	        uni.$TUIKit
	          .deleteConversation(value)
	          .then(function (imResponse) {
	            //删除成功。
	            const { conversationID } = imResponse.data; // 被删除的会话 ID。
	          })
	          .catch(function (imError) {
	            console.warn('deleteConversation error:', imError); // 删除会话失败的相关信息
	          });
	      }
	      if (e.index == '2') {
	        const list = this.conversationList;
	        const show = list.map(item => {
	          return item.conversationID;
	        });
	        const num = value.substring(0, 3);
	        if (num === 'C2C') {
	          const user = value.slice(3);
	          if (list[show.indexOf(value)].messageRemindType === 'AcceptNotNotify') {
	            uni.$TUIKit
	              .setMessageRemindType({
	                userIDList: [user],
	                messageRemindType: this.TIM.TYPES.MSG_REMIND_ACPT_AND_NOTE,
	              })
	              .then(function (imResponse) {
	                // 设置成功后 SDK 会触发 TIM.EVENT.CONVERSATION_LIST_UPDATED 事件（遍历列表，并读取 Conversation.messageRemindType）
	                const { successUserIDList, failureUserIDList } = imResponse.data;
	              })
	              .catch(function (imError) {
	                console.warn('setMessageRemindType error:', imError);
	              });
	          }
	          if (list[show.indexOf(value)].messageRemindType === 'AcceptAndNotify') {
	            uni.$TUIKit
	              .setMessageRemindType({
	                userIDList: [user],
	                messageRemindType: this.TIM.TYPES.MSG_REMIND_ACPT_NOT_NOTE,
	              })
	              .then(function (imResponse) {
	                // 设置成功后 SDK 会触发 TIM.EVENT.CONVERSATION_LIST_UPDATED 事件（遍历列表，并读取 Conversation.messageRemindType）
	                const { successUserIDList, failureUserIDList } = imResponse.data;
	              })
	              .catch(function (imError) {
	                console.warn('setMessageRemindType error:', imError);
	              });
	          }
	          if (list[show.indexOf(value)].messageRemindType === '') {
	            list[show.indexOf(value)].messageRemindType = 'AcceptNotNotify';
	          }
	        }
	        if (num === 'GRO') {
	          const groupID = value.slice(5);
	          if (list[show.indexOf(value)].messageRemindType === 'AcceptNotNotify') {
	            uni.$TUIKit
	              .setMessageRemindType({
	                groupID: groupID,
	                messageRemindType: this.TIM.TYPES.MSG_REMIND_ACPT_AND_NOTE,
	              })
	              .then(function (imResponse) {})
	              .catch(function (imError) {
	                console.warn('setMessageRemindType error:', imError);
	              });
	          }
	          if (list[show.indexOf(value)].messageRemindType === 'AcceptAndNotify') {
	            uni.$TUIKit
	              .setMessageRemindType({
	                groupID: groupID,
	                messageRemindType: this.TIM.TYPES.MSG_REMIND_ACPT_NOT_NOTE,
	              })
	              .then(function (imResponse) {})
	              .catch(function (imError) {
	                console.warn('setMessageRemindType error:', imError);
	              });
	          }
	        }
	      }
	    },
	    handleRouter() {
	      uni.showToast({
	        title: '跳转',
	        icon: 'none',
	      });
	    },
	    addBtn() {
	//       uni.showActionSheet({
	//         itemList: ['添加好友', '创建群聊', '加入群聊', '扫一扫'],
	//         success: res => {
	//           switch (res.tapIndex + 1) {
	//             case 1:
	//               uni.navigateTo({
	//                 url: '/im/conversation/create-conversation/create',
	//               });
	//               break;
	
	//             case 2:
	//               uni.navigateTo({
	//                 url: '/im/group/create-group/create',
	//               });
	//               break;
	
	//             case 3:
	//               uni.navigateTo({
	//                 url: '/im/group/join-group/join',
	//               });
	//               break;
	//             case 4:
	//               uni.scanCode({
	//                 success: function (res) {
	//                   console.log('条码类型：' + res.scanType);
	//                   console.log('条码内容：' + res.result);
	//                 },
	//               });
	//               break;
	//             default:
	//               break;
	//           }
	      //   },
	      //   fail: res => {
	      //     console.log(res.errMsg);
	      //   },
	      // });
	    },
	    handleRoute(id) {
	      uni.navigateTo({
	        url: `/im/chat/chat?conversationID=${id}`,
	      });
	    },
	    onConversationListUpdated(event) {
	      // this.conversationList = event.data;
		  this.setList(event.data)
	    },
	
	    getConversationList() {
	      uni.$TUIKit.getConversationList().then(imResponse => {
	        // this.conversationList = imResponse.data.conversationList;
			this.setList(imResponse.data.conversationList)
	      });
	    },
		setList(list){
			let conversationList = [];
			for(let i in list){
				let conversation = list[i]
				conversation.conversationName = this.getConversationName(conversation),
				conversation.setConversationAvatar = this.setConversationAvatarHandler(conversation),
				conversation.timeago = this.caculateTimeago(conversation.lastMessage.lastTime * 1000)
				conversationList.push(conversation)
			}
			this.conversationList = conversationList;
		},
		getConversationName(conversation) {
		  if (conversation.type === "@TIM#SYSTEM") {
		    return "系统通知";
		  }
		
		  if (conversation.type === "C2C") {
		    return (
		      conversation.remark ||
		      conversation.userProfile.nick ||
		      conversation.userProfile.userID
		    );
		  }
		
		  if (conversation.type === "GROUP") {
		    return (
		      conversation.groupProfile.name || conversation.groupProfile.groupID
		    );
		  }
		},
		
		setConversationAvatarHandler(conversation) {
		  if (conversation.type === "@TIM#SYSTEM") {
		    return "https://jw-uniapp.oss-cn-beijing.aliyuncs.com/static/images/msg/system.png";
		  }
		
		  if (conversation.type === "C2C") {
		    return (
		      conversation.userProfile.avatar ||
		      "https://jw-uniapp.oss-cn-beijing.aliyuncs.com/static/images/avatar.png"
		    );
		  }
		
		  if (conversation.type === "GROUP") {
		    return (
		      conversation.groupProfile.avatar ||
		      "https://jw-uniapp.oss-cn-beijing.aliyuncs.com/static/images/gruopavatar.png"
		    );
		  }
		},
		caculateTimeago(dateTimeStamp) {
		  const minute = 1000 * 60; // 把分，时，天，周，半个月，一个月用毫秒表示
		
		  const hour = minute * 60;
		  const day = hour * 24;
		  const week = day * 7;
		  const now = new Date().getTime(); // 获取当前时间毫秒
		
		  const diffValue = now - dateTimeStamp; // 时间差
		
		  let result = "";
		
		  if (diffValue < 0) {
		    return;
		  }
		
		  const minC = diffValue / minute; // 计算时间差的分，时，天，周，月
		
		  const hourC = diffValue / hour;
		  const dayC = diffValue / day;
		  const weekC = diffValue / week;
		
		  if (weekC >= 1 && weekC <= 4) {
		    result = ` ${parseInt(weekC, 10)}周前`;
		  } else if (dayC >= 1 && dayC <= 6) {
		    result = ` ${parseInt(dayC, 10)}天前`;
		  } else if (hourC >= 1 && hourC <= 23) {
		    result = ` ${parseInt(hourC, 10)}小时前`;
		  } else if (minC >= 1 && minC <= 59) {
		    result = ` ${parseInt(minC, 10)}分钟前`;
		  } else if (diffValue >= 0 && diffValue <= minute) {
		    result = "刚刚";
		  } else {
		    const datetime = new Date();
		    datetime.setTime(dateTimeStamp);
		    const Nyear = datetime.getFullYear();
		    const Nmonth =
		      datetime.getMonth() + 1 < 10
		        ? `0${datetime.getMonth() + 1}`
		        : datetime.getMonth() + 1;
		    const Ndate =
		      datetime.getDate() < 10
		        ? `0${datetime.getDate()}`
		        : datetime.getDate();
		    result = `${Nyear}-${Nmonth}-${Ndate}`;
		  }
		
		  return result;
		}
	  },
	};
	
</script>
<style lang="scss" scoped>
	// .page {
	// 	position: fixed;
	// 	top: 0;
	// 	left: 0;
	// 	right: 0;
	// 	bottom: 0;
	// 	background: linear-gradient(#e3ecfb, #fdedf0, #fff, #fff);
	// }
	.color__{ color: #7B749C; }
	.text_32{ color: #fff; }
	.text_22{ color: #999999; }
	.content {
		// width: 750rpx;
		min-height: 100vh;
		background-size: 750rpx 100vh;
		//background-repeat: no-repeat;
		background-position: 0 0;

		.warp {
			width: 750rpx;
			margin: 0 auto;

			.nav-bar {
				display: flex;
				font-weight: 550;
				font-size: 34rpx;
				color: #ffffff;

				.title {
					width: 680rpx;
					text-align: center;
				}
			}

			.title {
				color: #ffffff;
				padding-left: 40rpx;
			}

			.scroll-Y {
				/* #ifdef H5 */
				height: calc(100vh - 290rpx);
				/* #endif */
				/* #ifdef MP */
				height: calc(100vh - 126rpx);
				/* #endif */
			}
		}
	}


	.item {
		position: relative;
		box-sizing: border-box;
		padding: 20rpx 0 0rpx 30rpx;
		width: 96%;
		left:2%;
		background: rgba(255, 255, 255, 0.06);
		border-radius: 24rpx;
		margin-bottom: 20rpx;

		.item-img {
			width: 100rpx;
			height: 100rpx;
			margin-right: 20rpx;
			border-radius: 10rpx;
			margin-bottom: 20rpx;
			overflow: hidden;
			image{
				width: 100rpx;
				height: 100rpx;
			}

		}

		.item-UNREAD {
			position: absolute;
			top: 6rpx;
			left: 120rpx;
			min-width: 40rpx;
			height: 40rpx;
			text-align: center;
			line-height: 40rpx;
			border-radius: 20rpx;
			background-color: #ff0000;
		}

		.item-r {
			position: relative;

			.name {
				width: 100%;
				box-sizing: border-box;
				padding-right: 20rpx;
				margin-bottom: 15rpx;
			}

			.text {
				width: 100%;
				box-sizing: border-box;
				padding-right: 40rpx;
			}

			.m-line {
				position: absolute;
				bottom: 0;
				left: 0;
				right: 0;
				width: 100%;
			}
		}

	}
</style>